/*
 * @Description:
 * @Author: your name
 * @version:
 * @Date: 2024-05-09 13:30:09
 * @LastEditors: your name
 * @LastEditTime: 2025-04-18 11:12:45
 */
import api from "./request";
import _ from "lodash";
import { lineColors } from "@/store/staticData";
import { CoordTransform } from "@/cesiumTools/mapPlugin.js";

export const getLine = async (params) => {
  try {
    const { data, code } = await api.get(`/getLine`, { params });
    if (code === 200) {
      const result = data.map((item, index) => {
        const { xs, ys, stationsList } = item;
        const colorIndex = index % lineColors.length;
        const color = lineColors[colorIndex];
        item.color = color;
        item.checked = true;
        // 整理坐标
        const xpos = xs.split(",").map((item) => parseFloat(item));
        const ypos = ys.split(",").map((item) => parseFloat(item));
        let positions = [];
        if (xpos.length === ypos.length) {
          xpos.forEach((item, index) => {
            const [lng, lat] = CoordTransform.GCJ02ToWGS84(item, ypos[index]);

            positions.push({
              lng,
              lat,
            });
          });
        }
        item.paths = positions;

        if (stationsList.length) {
          item.stationsList = stationsList.map((station) => {
            const { xy_coords, ...rest } = station;
            const [lng, lat] = xy_coords.split(";").map((item) => Number(item));
            const [lngWgs84, latWgs84] = CoordTransform.GCJ02ToWGS84(lng, lat);
            return { position: { lng: lngWgs84, lat: latWgs84 }, ...rest };
          });
        }
        // 进一步处理数据，将路径上与站点最接近的点，标记为站点路径
        let currentPoint = null;
        item.paths = item.paths.map((path, index) => {
          const { lng: lngPath, lat: latPath } = path;
          const samePoint = item.stationsList.find((station) => {
            const {
              position: { lng, lat },
            } = station;
            if (
              lng.toFixed(3) === lngPath.toFixed(3) &&
              lat.toFixed(3) === latPath.toFixed(3)
            ) {
              return true;
            } else {
              return false;
            }
          });
          if (samePoint) {
            currentPoint = samePoint.name;
            return {
              ...path,
              name: samePoint.name,
            };
          } else {
            return {
              ...path,
              name: `${currentPoint}-${index}`,
            };
          }
        });
        item.paths = _.uniqBy(item.paths, (item) => item.name);

        return item;
      });
      return result;
    } else {
      return [];
    }
  } catch (error) {
    console.log(error);
  }
};

const transPosition = (locationStr) => {
  const [lng, lat] = locationStr.split(",").map((item) => Number(item));
  const [lngWgs84, latWgs84] = CoordTransform.GCJ02ToWGS84(lng, lat);
  return {
    lng: lngWgs84,
    lat: latWgs84,
  };
};

export const getLinePlan = async (params) => {
  const result = await api.get(`/getLinePlan`, { params });
  const { code, data } = result;
  if (code === 200) {
    const { segments } = data;
    if (segments.length) {
      segments.forEach((item) => {
        const {
          bus: { buslines },
        } = item;
        if (buslines?.length) {
          buslines.forEach((d) => {
            // 处理坐标投影系问题
            d.arrival_stop.location = transPosition(d.arrival_stop.location);
            d.departure_stop.location = transPosition(d.departure_stop.location);
            d.via_stops.forEach((s) => {
              s.location = transPosition(s.location);
            });
            let positionList = d.polyline.polyline.split(";");
            positionList = positionList.map((pos, index) => {
              return transPosition(pos);
            });
            d.polyline = positionList;
          });
        }
      });
    }
  }
  return result;
};
export const getStationInfo = (params) =>
  api.get(`/getStationInfo`, { params });

// https://restapi.amap.com/v3/weather/weatherInfo?parameters
export const getWeather = async () => {
  const params = {
    key: "934bdde4c3d4738b0abd16bdffd0b8f7",
    city: "420100",
  };

  const data = await api.get(
    "https://restapi.amap.com/v3/weather/weatherInfo",
    { params }
  );
  return data;
};
